package phoenixAAD.WifiFlashDrive.SimplifiedExpandableListAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import phoenixAAD.WifiFlashDrive.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

public class SimplifiedExpandListAdapter{
	private static final String TEXT = "text", IMAGE ="image";
	
	/**
	 * Simplifies the over-complicated SimpleExpandListAdapter creation 
	 * @param context - context of the activity
	 * @param sections - the class that contains the resource id needed
	 * @return the adapter created
	 */
	public static SimpleExpandableListAdapter getAdapter(Context context, SectionSet[] sections)
	{
		
		ArrayList<Map<String, String>> groupList = new ArrayList<Map<String, String>>();
		ArrayList<List<Map<String, Object>>> childList = new ArrayList<List<Map<String, Object>>>();
		
		for(int i = 0; i < sections.length; i++)
		{
			String title = context.getResources().getString(sections[i].getTitle());
			String text = context.getResources().getString(sections[i].getText());
			
			HashMap<String, String> groupMap = new HashMap<String, String>();
			groupMap.put(TEXT, title);
			groupList.add(groupMap);
			
			ArrayList<Map<String, Object>> child = new ArrayList<Map<String,Object>>();
			HashMap<String, Object> childMap = new HashMap<String, Object>();
			childMap.put(TEXT, text);
			// if the image is not supplied
			if(sections[i].getImage() == SectionSet.NULL)
				childMap.put(IMAGE, null);
			else
				childMap.put(IMAGE, context.getResources().getDrawable(sections[i].getImage()));
			child.add(childMap);
			childList.add(child);
		}
		
		return new SimpleExpandableListAdapter(
				context, 
				groupList,
				android.R.layout.simple_expandable_list_item_1,
				new String[] {TEXT},
				new int[] {android.R.id.text1},
				childList,
				R.layout.item_image,
				null,
				new int[] {}
				){

					@SuppressWarnings("unchecked")
					@Override
					public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
						View view = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
						TextView textView = (TextView)view.findViewById(R.id.text_item);
						textView.setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TEXT) );
						Drawable drawable = (Drawable) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(IMAGE);
						ImageView imageView = (ImageView)view.findViewById(R.id.image_item);
						imageView.setImageDrawable(drawable);
						
						return view;
					}

			
		};
	}

}
